/*
 * Copyright (C) 2023, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

#include "sidebar-dbus-service.h"
#include "sidebaradaptor.h"

#include <QDBusConnection>
#include <QStringLiteral>
#include <QDebug>

#define SIDEBAR_DBUS_SERVICE          "org.ukui.Sidebar"
#define SIDEBAR_DBUS_PATH             "/org/ukui/Sidebar"
#define SIDEBAR_DBUS_INTERFACE        "org.ukui.Sidebar"

namespace Sidebar {

SidebarDbusService::SidebarDbusService(SideBarApplication *parent)
    : QObject(parent), QDBusContext(), m_adaptor(new SidebarAdaptor(this))
{
    QDBusReply<QDBusConnectionInterface::RegisterServiceReply> reply =
        QDBusConnection::sessionBus().interface()->registerService(SIDEBAR_DBUS_SERVICE,
                                                                   QDBusConnectionInterface::ReplaceExistingService,
                                                                   QDBusConnectionInterface::DontAllowReplacement);

    if (reply.value() != QDBusConnectionInterface::ServiceNotRegistered) {
        bool res = QDBusConnection::sessionBus().registerObject(SIDEBAR_DBUS_PATH, this);
        if (!res) {
            QDBusConnection::sessionBus().interface()->unregisterService(SIDEBAR_DBUS_SERVICE);
        }
    }
}

SideBarApplication *SidebarDbusService::parent()
{
    return qobject_cast<SideBarApplication*>(QObject::parent());
}

void SidebarDbusService::sidebarActive()
{
    parent()->requestSidebar(SideBarApplication::Active);
}

void SidebarDbusService::shortcutsActive()
{
    parent()->requestSidebar(SideBarApplication::Active);
}

void SidebarDbusService::active(const QString &module)
{
    if (module == "control") {
        parent()->requestSidebar(SideBarApplication::Active);
    } else {
        parent()->requestNotificationCenter(SideBarApplication::Active);
    }
}

} // Sidebar
